# -*- coding: utf-8 -*- #
"""
Time                2022/11/14 14:32
Author:             mingfeng (SunnyQjm)
Email               mfeng@linux.alibaba.com
File                crud.py
Description:
"""
from typing import Union, Tuple, List
from sqlalchemy.orm import Session
from sqlalchemy import insert, desc, select
from app.models import AuditLog, NodeLog
from app import models, schemas, query
from app.database import SessionLocal

################################################################################################
# Define database crud here
################################################################################################

################################################################################################
# NodeLog
################################################################################################


def create_node_log(db: Session, node_log: schemas.NodeLogCreate) -> models.NodeLog:
    """Create Node Log

    Args:
           db (Session): _description_
           node_log (schemas.NodeLog): _description_

    Returns:
           models.NodeLog: _description_
    """
    db_node_log = models.NodeLog(**node_log.dict())
    db.add(db_node_log)
    db.commit()
    db.refresh(db_node_log)
    return db_node_log


def get_node_logs(
    db: Session, query_params: query.NodeLogQueryParams
) -> Tuple[List[models.NodeLog], int]:
    # 1. Get total count after apply filter
    total_count = query_params.get_count_by(db, models.NodeLog.id)

    # 2. Get alert list after apply sorter and paging
    alert_list = (
        query_params.get_query_builder(db)
        .apply_filter()
        .apply_sorter()
        .apply_paging()
        .build()
        .all()
    )

    return alert_list, total_count


################################################################################################
# AuditLog
################################################################################################


def create_audit_log(db: Session, audit_log: schemas.AuditLogCreate) -> models.AuditLog:
    """Create Audit Log

    Args:
              db (Session): _description_
              audit_log (schemas.AuditLog): _description_

    Returns:
              models.AuditLog: _description_
    """
    db_audit_log = models.AuditLog(**audit_log.dict())
    db.add(db_audit_log)
    db.commit()
    db.refresh(db_audit_log)
    return db_audit_log


def get_audit_logs(
    db: Session, query_params: query.AuditLogQueryParams
) -> Tuple[List[models.AuditLog], int]:
    # 1. Get total count after apply filter
    total_count = query_params.get_count_by(db, models.AuditLog.id)

    # 2. Get alert list after apply sorter and paging
    alert_list = (
        query_params.get_query_builder(db)
        .apply_filter()
        .apply_sorter()
        .apply_paging()
        .build()
        .all()
    )

    return alert_list, total_count